import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Row, Col, Button, Form, Divider, Table, Popconfirm } from 'antd';
import AddRuleForm from './components/add';
import EditRuleForm from './components/edit';

@connect(({ product, loading }) => ({
  product,
  loading: loading.models.product,
}))
@Form.create()
class TcpProtocol extends PureComponent {
  state = {
    modalVisible: false,
    isShowPid: false,
    editModalVisible: false,
  };

  renderRuleViewColumns = data =>
    data.map(item => ({
      title: item.name,
      key: item.name,
      dataIndex: item.name,
    }));

  dataSource = data => {
    const obj = {};
    for (let i = 0, l = data.length; i < l; i += 1) {
      const param = data[i].name;
      const len = data[i].fixedLength ? `${data[i].fixedLength}字节` : '';
      const content = data[i].fixedContent ? data[i].fixedContent : '';
      if (len !== '' && content !== '') {
        obj[param] = `${len},${content}`;
      } else if (len === '' && content === '') {
        obj[param] = '';
      } else if (len === '' && content !== '') {
        obj[param] = content;
      } else if (len !== '' && content === '') {
        obj[param] = len;
      }
    }
    return new Array(obj);
  };

  ruleColumns = [
    {
      key: 'order',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.order' }),
      render: (text, record, index) => index + 1,
    },
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.name' }),
      dataIndex: 'name',
    },
    {
      key: 'ruleTypeId',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.type' }),
      dataIndex: 'ruleTypeId',
      render: (text, record) => {
        if (record.ruleTypeId === 1) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.flag' });
        }
        if (record.ruleTypeId === 2) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.fixed' });
        }
        if (record.ruleTypeId === 3) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.length' });
        }
        if (record.ruleTypeId === 4) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.data' });
        }
        if (record.ruleTypeId === 5) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.check' });
        }
        if (record.ruleTypeId === 6) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.datavalue' });
        }
        if (record.ruleTypeId === 7) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.devsn' });
        }
        return null;
      },
    },
    {
      key: 'fixedLength',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.fixedlength' }),
      dataIndex: 'fixedLength',
    },
    {
      key: 'fixedContent',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.fixedcontent' }),
      dataIndex: 'fixedContent',
    },
    {
      key: 'propertyLabel',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.property' }),
      dataIndex: 'propertyLabel',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.editView(record.id, false)}>
            <FormattedMessage id="app.dm.product.protocol.tcp.table.action.edit" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280 }}>
                <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                  <span>
                    {formatMessage(
                      { id: 'app.dm.product.protocol.tcp.del.confirm' },
                      { name: record.name },
                    )}
                  </span>
                </div>
              </div>
            }
            onConfirm={() => this.handleMainRuleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.dm.product.protocol.tcp.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  childRuleColumns = [
    {
      key: 'order',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.order' }),
      render: (text, record, index) => index + 1,
    },
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.name' }),
      dataIndex: 'name',
    },
    {
      key: 'pidName',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.pid' }),
      dataIndex: 'pidName',
    },
    {
      key: 'ruleTypeId',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.type' }),
      dataIndex: 'ruleTypeId',
      render: (text, record) => {
        if (record.ruleTypeId === 1) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.flag' });
        }
        if (record.ruleTypeId === 2) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.fixed' });
        }
        if (record.ruleTypeId === 3) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.length' });
        }
        if (record.ruleTypeId === 4) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.data' });
        }
        if (record.ruleTypeId === 5) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.check' });
        }
        if (record.ruleTypeId === 6) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.datavalue' });
        }
        if (record.ruleTypeId === 7) {
          return formatMessage({ id: 'app.dm.product.protocol.tcp.table.type.devsn' });
        }
        return null;
      },
    },
    {
      key: 'fixedLength',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.fixedlength' }),
      dataIndex: 'fixedLength',
    },
    {
      key: 'fixedContent',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.fixedcontent' }),
      dataIndex: 'fixedContent',
    },
    {
      key: 'propertyLabel',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.property' }),
      dataIndex: 'propertyLabel',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.product.protocol.tcp.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.editView(record.id, true)}>
            <FormattedMessage id="app.dm.product.protocol.tcp.table.action.edit" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280 }}>
                <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                  <span>
                    {formatMessage(
                      { id: 'app.dm.product.protocol.tcp.del.confirm' },
                      { name: record.name },
                    )}
                  </span>
                </div>
              </div>
            }
            onConfirm={() => this.handleChildRuleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.dm.product.protocol.tcp.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch, protocolId, productId } = this.props;
    dispatch({
      type: 'product/fetchTcpMainProtocol',
      payload: protocolId,
    });
    dispatch({
      type: 'product/fetchTcpChildProtocol',
      payload: protocolId,
    });
    dispatch({
      type: 'product/fetchRuleTypes',
    });
    dispatch({
      type: 'product/fetchProductProps',
      payload: productId,
    });
  }

  clearRule = () => {
    const { dispatch, protocolId } = this.props;
    dispatch({
      type: 'product/clearTcpRule',
      payload: { id: protocolId },
    });
  };

  editView = (id, pidShow) => {
    const { dispatch } = this.props;
    const { handleEditModalVisible } = this;
    this.setState({
      isShowPid: pidShow,
    });
    dispatch({
      type: 'product/fetchTcpInfo',
      payload: id,
      handleEditModalVisible,
    });
  };

  handleEditModalVisible = flag => {
    this.setState({
      editModalVisible: !!flag,
    });
  };

  handleChildRuleDelete = id => {
    const { dispatch, protocolId } = this.props;
    dispatch({
      type: 'product/delTcpChildProtocol',
      payload: id,
      protocolId,
    });
  };

  handleMainRuleDelete = id => {
    const { dispatch, protocolId } = this.props;
    dispatch({
      type: 'product/delTcpMainProtocol',
      payload: id,
      protocolId,
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  addMainSegmentHandle = () => {
    this.handleModalVisible(true);
    this.setState({
      isShowPid: false,
    });
  };

  addChildSegmentHandle = () => {
    this.handleModalVisible(true);
    this.setState({
      isShowPid: true,
    });
  };

  handleAdd = (fieldsValue, form) => {
    const {
      dispatch,
      protocolId,
      product: { tcpMainProtocolList, tcpChildProtocolList },
    } = this.props;
    const { handleModalVisible } = this;

    const { isShowPid } = this.state;
    let isAddMainSegment = true;
    let ruleOrder = 1;
    if (isShowPid === true) {
      isAddMainSegment = false;
      ruleOrder = tcpChildProtocolList.length + 1;
    } else {
      ruleOrder = tcpMainProtocolList.length + 1;
    }
    const contentParams = {
      ruleTypeId: fieldsValue.ruleTypeId,
      includeIds: fieldsValue.includeIds,
      dataIds: fieldsValue.dataIds,
      conditionIds: fieldsValue.conditionIds,
      conditionContent: fieldsValue.conditionContent,
      checkRuleId: fieldsValue.checkRuleId,
      isFixedLength: fieldsValue.isFixedLength,
      fixedLength: fieldsValue.fixedLength,
      isFixedContent: fieldsValue.isFixedContent,
      fixedContent: fieldsValue.fixedContent,
      propertyLabel: fieldsValue.propertyLabel,
      desc: fieldsValue.desc,
    };
    const protocolIdParam = protocolId;
    dispatch({
      type: 'product/addTcpProtocol',
      payload: {
        pid: fieldsValue.pid,
        protocolId: protocolIdParam,
        name: fieldsValue.name,
        content: JSON.stringify(contentParams),
        order: ruleOrder,
      },
      form,
      isAddMainSegment,
      handleModalVisible,
    });
  };

  handleEdit = (fieldsValue, form) => {
    const { dispatch } = this.props;
    const { handleEditModalVisible } = this;
    const { isShowPid } = this.state;
    let isEditMainSegment = true;
    if (isShowPid === true) {
      isEditMainSegment = false;
    }
    const contentParams = {
      ruleTypeId: fieldsValue.ruleTypeId,
      includeIds: fieldsValue.includeIds,
      dataIds: fieldsValue.dataIds,
      conditionIds: fieldsValue.conditionIds,
      conditionContent: fieldsValue.conditionContent,
      checkRuleId: fieldsValue.checkRuleId,
      isFixedLength: fieldsValue.isFixedLength,
      fixedLength: fieldsValue.fixedLength,
      isFixedContent: fieldsValue.isFixedContent,
      fixedContent: fieldsValue.fixedContent,
      propertyLabel: fieldsValue.propertyLabel,
      desc: fieldsValue.desc,
    };
    dispatch({
      type: 'product/editTcpProtocol',
      payload: {
        id: fieldsValue.id,
        pid: fieldsValue.rulePid,
        protocolId: fieldsValue.protocolId,
        name: fieldsValue.name,
        content: JSON.stringify(contentParams),
      },
      form,
      isEditMainSegment,
      handleEditModalVisible,
    });
  };

  render() {
    const {
      product: {
        tcpMainProtocolList,
        tcpChildProtocolList,
        ruleTypeList,
        productPropList,
        protocolDetail,
      },
      loading,
    } = this.props;
    const { modalVisible, isShowPid, editModalVisible } = this.state;

    const AddModalProps = {
      handleModalVisible: this.handleModalVisible,
      handleAdd: this.handleAdd,
      ruleTypes: ruleTypeList,
      productProps: productPropList,
      rules: tcpMainProtocolList,
    };
    const EditModalProps = {
      handleModalVisible: this.handleEditModalVisible,
      handleEdit: this.handleEdit,
      ruleTypes: ruleTypeList,
      productProps: productPropList,
      rules: tcpMainProtocolList,
      detail: protocolDetail,
    };
    return (
      <Fragment>
        <Row>
          <Col span={12}>
            <span style={{ fontWeight: 'bold', fontSize: 20 }}>
              <FormattedMessage id="app.dm.product.protocol.rule.view" />
            </span>
          </Col>
          <Col style={{ textAlign: 'right' }}>
            <Popconfirm
              title={
                <div style={{ width: 280 }}>
                  <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                    <span>
                      {formatMessage({ id: 'app.dm.product.protocol.rule.clear.confirm' })}
                    </span>
                  </div>
                </div>
              }
              onConfirm={() => this.clearRule()}
            >
              <Button type="primary">
                <FormattedMessage id="app.dm.product.protocol.rule.clear" />
              </Button>
            </Popconfirm>
          </Col>
        </Row>
        <Row>
          <Table
            columns={this.renderRuleViewColumns(tcpMainProtocolList)}
            dataSource={this.dataSource(tcpMainProtocolList)}
            loading={loading}
            rowKey="id"
            pagination={false}
            style={{ marginTop: 5 }}
          />
        </Row>
        <Row style={{ marginTop: 20 }}>
          <Col span={12}>
            <span style={{ fontWeight: 'bold', fontSize: 20 }}>
              <FormattedMessage id="app.dm.product.protocol.rule.mainsegment" />
            </span>
          </Col>
          <Col style={{ textAlign: 'right' }}>
            <Button onClick={() => this.addMainSegmentHandle()} type="primary">
              <FormattedMessage id="app.dm.product.protocol.rule.mainsegment.add" />
            </Button>
          </Col>
        </Row>
        <Row>
          <Table
            columns={this.ruleColumns}
            dataSource={tcpMainProtocolList}
            loading={loading}
            rowKey="id"
            pagination={false}
            style={{ marginTop: 5 }}
          />
        </Row>
        <Row style={{ marginTop: 20 }}>
          <Col span={12}>
            <span style={{ fontWeight: 'bold', fontSize: 20 }}>
              <FormattedMessage id="app.dm.product.protocol.rule.field" />
            </span>
          </Col>
          <Col style={{ textAlign: 'right' }}>
            <Button onClick={() => this.addChildSegmentHandle()} type="primary">
              <FormattedMessage id="app.dm.product.protocol.rule.field.add" />
            </Button>
          </Col>
        </Row>
        <Row>
          <Table
            columns={this.childRuleColumns}
            dataSource={tcpChildProtocolList}
            loading={loading}
            rowKey="id"
            pagination={false}
            style={{ marginTop: 5 }}
          />
        </Row>
        <AddRuleForm {...AddModalProps} modalVisible={modalVisible} isShowPid={isShowPid} />
        <EditRuleForm {...EditModalProps} modalVisible={editModalVisible} isShowPid={isShowPid} />
      </Fragment>
    );
  }
}
export default TcpProtocol;
